/**
 * @file   TTF001File.java
 * @date   2012-11-12上午10:03:55
 * @author User
 */
package com.gzceb.zhgjj.model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import com.gzceb.zhgjj.mina.MinaConstants;
import com.gzceb.zhgjj.mina.TTF001.ReceivedTTF001File;

/**
 * <p>TTF001接收文件处理类。</p>
 *
 * @date   2012-11-12上午10:03:55 
 * @author liqing
 * @description 
 */
public class TTF001File {
	private  final Log logger = LogFactory.getLog(TTF001File.class);
	
	private String fileName;
	private String fileCont="";  //发送来的文件内容先保存在String中。
	public String strPath;
	
	public TTF001File(String strPath){
		this.strPath = strPath;
	}
	
	public void setFileName(String fileName){
		this.fileName = fileName;
	}
	/**
	 * 处理接收到的信息，保存成文件
	 */
	public String ProcRcvFile(String message){
		//如果接收的是 F_NAME+文件名，则反馈成功
    	String regx = MinaConstants.F_NAME.getValue() + "L[ABCD]\\w{18}";
    	String rspStr = "";
    	if(message.matches(regx)){
    		fileName = message.substring(1);
    		logger.info("get the right file name: " + fileName);
    		rspStr = MinaConstants.F_EIXOK.getValue() + MinaConstants.F_NINESPACE.getValue();
    		
    	}
    	else if (message.matches(MinaConstants.F_DATA.getValue() + ".{1,200}")){
    		// 如果接收的是文本正文，应该每次传输200个字节，最后一组可能小于200
    		// 所以接收到200以上字节的内容就是错误的
    		fileCont += message.substring(1);
    		logger.info("get file content... continue..");
    		rspStr = MinaConstants.F_ACK.getValue() + MinaConstants.F_NINESPACE.getValue();
    		
    	}
    	else if(message.equals(MinaConstants.F_OVER.getValue())){
    		
    		BufferedWriter bw = null;
    		try{
    			bw = new BufferedWriter(new FileWriter(strPath + fileName));
    			int i;
    			while((i=fileCont.indexOf(System.getProperty("line.separator") )) != -1){
    				String tmpstr = fileCont.substring(0, i-1);
    				bw.write(tmpstr);
    				bw.newLine();
    				fileCont=fileCont.substring(i+1);
    			}
    			bw.write(fileCont);
    			logger.info("the file received successfully.");
    			rspStr = MinaConstants.F_OVER.getValue();
    			
    		}catch(Exception ec){
    			logger.error("Errors happended when writing to file " + strPath+fileName
    					+ "\n" + ec);
    			rspStr = MinaConstants.F_NAK.getValue()+ MinaConstants.F_NINESPACE.getValue();
    		}finally{
    			if (bw != null) {
    				try {
    					bw.close();
    				} catch (Exception ec) {
    					logger.error("Errors happened when closinig BufferedWriter.\n" + ec);
    					rspStr = MinaConstants.F_NAK.getValue()+ MinaConstants.F_NINESPACE.getValue();
    					
    				}
    			}
    			
    		}

    	}
    	return rspStr;	
	}
	
	/**
	 * 发送本地处理过的响应文件
	 */
	public String ProcRspFile(String message){
		String rspStr = "";
		
		//中心先获取银行给的响应文件名后，返回1+9个空格
		if( (MinaConstants.F_EIXOK.getValue() + MinaConstants.F_NINESPACE.getValue()).equals(message)){
			BufferedReader br = null;
			logger.info("接收到中心的响应，开始在本地读取响应文件。");
			try{
				br = new BufferedReader(new FileReader(strPath + fileName));
				String tmpStr = null;
				while( (tmpStr = br.readLine()) != null){
					fileCont += tmpStr;
					fileCont += System.getProperty("line.separator");
				}
				logger.info("响应文件读取完毕。文件名：" + fileName);
				//第一次发送前200字节内容后，将fileCont去掉前200字节，以便后面接收到响应后循环发送剩余字节
				if(fileCont.length()<200){
					rspStr = MinaConstants.F_DATA.getValue()+ fileCont;
					fileCont="";
				}else{
					rspStr = MinaConstants.F_DATA.getValue() + fileCont.substring(0, 200);
					fileCont = fileCont.substring(200);
				}
			}catch(Exception e){
				logger.error("Error happended when reading rsp file: " + fileName + "\n" + e.getMessage());
				//如果有异常，响应就置为NAK，透传给上层去关闭session
				rspStr = MinaConstants.F_NAK.getValue();
			}finally{
    			if (br != null) {
    				try {
    					br.close();
    				} catch (Exception ec) {
    					logger.error("Errors happened when closinig BufferedReader.\n" + ec);
    					rspStr = MinaConstants.F_NAK.getValue();
    					
    				}
    			}
    			
    		}
			
		}else if( (MinaConstants.F_ACK.getValue()+ MinaConstants.F_NINESPACE.getValue()).equals(message) ){
			if(fileCont.isEmpty()){
				rspStr = MinaConstants.F_OVER.getValue();
			}else if (fileCont.length()<200){
				rspStr = fileCont;
				fileCont = "";
			}else{
				rspStr = MinaConstants.F_DATA.getValue() + fileCont.substring(0, 200);
				fileCont = fileCont.substring(200);
			}
		}else if( (MinaConstants.F_NAK.getValue() + MinaConstants.F_NINESPACE).equals(message) ){
			//如果中心出现接收错误，这里就把返回的信息透传给上层，上层完成session关闭
			rspStr = MinaConstants.F_NAK.getValue();
		}
		
		return rspStr;
	}

}
